<template>
  <Page :withAppBar="true">
    <!-- 1、头部 -->
    <AppBar class="app-bar" v-if="globalConfig.inApp">
      <!-- 左侧返回箭头 -->
      <img
        slot="left"
        class="icon-back"
        src="../../assets/images/icon_arrow_back.png"
        @click="back()"
      />
      <section style="color:white; font-size: 22px" slot="center">{{ isAdd ? "add content": "edit content"}}</section>
    </AppBar>

    <!-- 2、内容 -->
    <appContent>
      <section class="add-content">
        <!-- 信息录入 -->
        <mu-container>
          <mu-form ref="form" :model="validateForm" class="mu-demo-form">
            <mu-form-item label="标题" prop="title" :rules="usernameRules">
              <mu-text-field v-model="validateForm.title" prop="title"></mu-text-field>
            </mu-form-item>
            <mu-form-item label="内容" prop="text" :rules="passwordRules">
                <mu-text-field type="text" v-model="validateForm.text" prop="text"></mu-text-field>
            </mu-form-item>
            <div class="bottom-grounp">
              <mu-button color="primary" @click="submit">提交</mu-button>
              <mu-button @click="clear">重置</mu-button>
            </div>
          </mu-form>
        </mu-container>
      </section>
    </appContent>
  </Page>
</template>

<script>
import { mapState } from 'vuex';
export default {
  name: 'todo',
  components: {
  },
  data() {
    return {
      isAdd: false,
      usernameRules: [
        { validate: (val) => !!val, message: '必须填写标题'}
      ],
      passwordRules: [
        { validate: (val) => !!val, message: '必须填写内容'}
      ],
      validateForm: {
        title: '',
        text: '',
        id:''
      }
    }
  },

  computed:{
    // 获取vuex中的数据
    ...mapState({
      totalList: state => state.todo.totalList // todo列表数据
    }),
  },

  created() {
    // 判断是新增还是编辑
    const todoId = this.$route.query.todoId
    if(todoId){
      this.isAdd = false
      // 编辑的内容
      const todoObj = this.totalList.find(val=>todoId === val.id)
      this.validateForm.title = todoObj.title
      this.validateForm.text = todoObj.text
      this.validateForm.id = todoObj.id
    }else{
      this.isAdd = true
    }
  },
  methods: {
    // 提交
    submit () {
      this.$refs.form.validate().then((result) => {
        console.log('form valid: ', result)
        if(result){
          console.log('输入的内容: ', this.validateForm)
          let todoContent = this.totalList
          // 新增
          if(this.isAdd){
            todoContent.push({
              complete: false,
              title: this.validateForm.title,
              text: this.validateForm.text,
              id: this.uuid()         
            })
          }else{
              // 编辑
              let editIndex = todoContent.findIndex(val=>val.id === this.validateForm.id)
              todoContent[editIndex].title = this.validateForm.title
              todoContent[editIndex].text = this.validateForm.text
            }
            // 保存数据到vuex
            this.$store.commit("todo/setState", {
              attr: "totalList",
              data: todoContent
            });
            // 返回
            this.back()
          }
      });
    },

    // 清空
    clear () {
      this.$refs.form.clear();
      this.validateForm = {
        title: '',
        text: '',
        id: this.validateForm.id,
      };
    },

    /**
     * 生成32位uuid
     */
    uuid(){
      let withLine = true; //带不带横线
      let len = 32; //长度为32
      let radix = 16; //16进制
      let chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
        ""
      );
      let uuid = [],
        i;
      radix = radix || chars.length;
      if (withLine) {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23];
        uuid[14] = "4";
        for (i = 0; i < len; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16);
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
          }
        }
      } else {
        for (i = 0; i < len; i++) {
            uuid[i] = chars[0 | (Math.random() * radix)];
        }
      }
      return uuid.join("");
    }  
  },
}
</script>

<style lang="scss" scoped>
.icon-back{
  width: 20px;
}
.add-content{
  margin: 60px 20px;
  padding: 10px 20px;
  background-color: #fff;
  box-shadow: 0 8px 10px 4px rgba(186, 190, 198, 0.3);
}
.bottom-grounp{
  display: flex;
  justify-content: space-around
}

</style>